import { ipcMain } from 'electron'
const { app, BrowserWindow } = require('electron')
const path = require('node:path')

let loadingWindow: typeof BrowserWindow | null = null
let mainWindow: typeof BrowserWindow | null = null

function createLoadingWindow() {
  loadingWindow = new BrowserWindow({
    width: 450,
    height: 300,
    frame: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  })
  loadingWindow.loadURL('http://localhost:3000/loading')
}

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  })
  mainWindow.loadURL('http://localhost:3000/')

  ipcMain.on('message', (event, arg) => {
    console.log('收到渲染进程的消息:', arg)
    const newWindow = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: false,
        preload: path.join(__dirname, './preload/preload.js'),
      },
    })
    newWindow.loadURL('http://localhost:3000/about')
    event.reply('message', '主进程已收到消息')
  })
}

app.whenReady().then(() => {
  createLoadingWindow()

  setTimeout(() => {
    if (loadingWindow) {
      loadingWindow.close()
      loadingWindow = null
    }
    createMainWindow()

    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
    })
  }, 3000)
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
